package com.sr.examination.exam.grade;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.sr.examination.R;
import com.sr.examination.main.MainActivity;
import com.sr.examination.net.Net;
import com.sr.examination.user.Account;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.ActivityStack;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.tl.commonlibrary.ui.adapter.ListViewAdapter;
import com.tl.commonlibrary.ui.adapter.ViewHolder;
import com.tl.commonlibrary.ui.beans.ExamGrade;
import com.tl.commonlibrary.ui.beans.User;
import com.tl.commonlibrary.ui.widget.CustomAlertDialog;
import com.tl.commonlibrary.ui.widget.TitleBar;

import java.util.ArrayList;

import retrofit2.Call;

/**
 * Created by JongSung on 18/2/25.
 */

public class ExamGradeActivity extends BaseFragmentActivity implements AdapterView.OnItemClickListener, ListViewAdapter.OnListViewAdapterListener<ExamGrade> {
    public static void start(Context context, int type) {
        Intent starter = new Intent(context, ExamGradeActivity.class);
        starter.putExtra("type", type);
        context.startActivity(starter);
    }

    public static final int TYPE_CREATE = 0;
    public static final int TYPE_UPDATE = 1;

    private ListView gradeLView;
    private ListViewAdapter<ExamGrade> adapter;
    private int type = TYPE_CREATE;
    private CustomAlertDialog confirmDialog;
    private CustomAlertDialog exitDialog;
    private boolean compatibleFinish = false;//创建考试级别时，如果请求失败，还是让用户可以退出当前界面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_exam_grade);
        type = getIntent().getIntExtra("type", TYPE_CREATE);

        gradeLView = findViewById(R.id.gradeLView);
        gradeLView.setDivider(new ColorDrawable(0x00000000));
        gradeLView.setDividerHeight(0);
        gradeLView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
//        ArrayList<GradeBean> datas = new ArrayList<>();
//        for (int i = 0; i < 4; i++) {
//            datas.add(new GradeBean());
//        }
//        adapter = new ListViewAdapter<GradeBean>(context, datas, R.layout.item_exam_grade, this);
        gradeLView.setOnItemClickListener(this);
        gradeLView.setAdapter(adapter);
        if (type == TYPE_CREATE) {
            getTitleBar().getLeftView().setVisibility(View.GONE);
            setTitle(getString(R.string.choose_exam_grade_create));
        } else if (type == TYPE_UPDATE) {
            setTitle(getString(R.string.choose_exam_grade_update));
        }
        findViewById(R.id.contentLayout).setVisibility(View.GONE);
        showLoading();
        dismissNoData();
        gradeLView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getExamGradeList();
            }
        }, 600);
    }

    private void setSaveButton() {
        String rightActionStr = "";
        if (type == TYPE_CREATE) {
            rightActionStr = getString(R.string.grade_sure);
        } else if (type == TYPE_UPDATE) {
            rightActionStr = getString(R.string.save);
        }
        getTitleBar().addAction(new TitleBar.TextAction(rightActionStr) {
            @Override
            public void performAction(View view) {
                if (type == TYPE_UPDATE) {
                    if (confirmDialog == null) {
                        confirmDialog = new CustomAlertDialog(context);
                        confirmDialog.setContent(getString(R.string.alert_exam_grade_update));
                        confirmDialog.setRightText(getString(R.string.save));
                        confirmDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                            @Override
                            public void onRightClicked(View view) {
                                setExamGrade();
                            }

                            @Override
                            public void onLeftClicked(View view) {

                            }
                        });
                    }
                    confirmDialog.show();
                } else {
                    setExamGrade();
                }
            }
        });
    }

    private void getExamGradeList() {
        Net.getExamGradeList(new RequestListener<BaseBean<ArrayList<ExamGrade>>>() {
            @Override
            public void onSuccess(Call<BaseBean<ArrayList<ExamGrade>>> call, BaseBean<ArrayList<ExamGrade>> response) {
                ArrayList<ExamGrade> examGrades = response.data;
                if (examGrades != null && !examGrades.isEmpty()) {
                    adapter = new ListViewAdapter<ExamGrade>(context, examGrades, R.layout.item_exam_grade, ExamGradeActivity.this);
                    gradeLView.setAdapter(adapter);
                    int userGrade = Account.isLogged() ? Account.getUser().getLevelId() : -1;
                    int i = 0;
                    for (i = 0; i < examGrades.size(); i++) {
                        if (examGrades.get(i).getLevelId() == userGrade) {
                            break;
                        }
                    }
                    if (i < examGrades.size()) {
                        gradeLView.setItemChecked(i, true);
                    }
                    setSaveButton();
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                } else {
                    UIUtils.showToast(getString(R.string.hint_get_exam_grade_list_failed));
                }
                dismissAll();
            }

            @Override
            public void onFailed(Call<BaseBean<ArrayList<ExamGrade>>> call, ErrorResponse errorResponse) {
                dismissAll();
            }
        });
    }

    private void setExamGrade() {
        if (adapter == null) {
            return;
        }
        int position = gradeLView.getCheckedItemPosition();
        if (position >= 0 && position < adapter.getCount()) {
            final int levelId = adapter.getItem(position).getLevelId();
            showProgressDialog(false);
            Net.setExamGrade(levelId, new RequestListener<BaseBean>() {
                @Override
                public void onSuccess(Call<BaseBean> call, BaseBean response) {
                    dismissAll();
                    if (response.isSuccessful()) {
                        User user = Account.getUser();
                        if (user != null) {
                            user.setLevelId(levelId);
                        }
                        Account.setUser(user);
                        if (ActivityStack.get().has(MainActivity.class) <= 0) {
                            MainActivity.start(context);
                        }
                        finish();
                    }
                }

                @Override
                public void onFailed(Call<BaseBean> call, ErrorResponse errorResponse) {
                    compatibleFinish = true;
                    dismissAll();
                }
            });

        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onFragmentTrigger(int tag, Bundle bundle) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onClickViewInListItem(View v) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (type == TYPE_CREATE) {
                if (!compatibleFinish) {
                    UIUtils.showToast("请确定选择考试级别~");
                } else {
                    showExitDialog();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void getView(ViewHolder viewHolder, ExamGrade entity, int position, View convertView, boolean isConvert, int itemViewType, ViewGroup parent) {
        TextView contentTView = viewHolder.getView(R.id.contentTView);
        View lineView = viewHolder.getView(R.id.lineView);
        contentTView.setText(entity.getName());
        if (position == adapter.getCount() - 1) {
            lineView.setVisibility(View.GONE);
        } else {
            lineView.setVisibility(View.VISIBLE);
        }
    }

    private void showExitDialog() {
        if (type == TYPE_CREATE) {
            if (exitDialog == null) {
                exitDialog = new CustomAlertDialog(context);
                exitDialog.setContent("尚未选择考试级别，确定退出吗？");
                exitDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                    @Override
                    public void onRightClicked(View view) {
                        if (ActivityStack.get().has(MainActivity.class) <= 0) {
                            MainActivity.start(context);
                        }
                        finish();
                    }

                    @Override
                    public void onLeftClicked(View view) {

                    }
                });
            }
            exitDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (confirmDialog != null) {
            confirmDialog.dismiss();
            confirmDialog = null;
        }
        if (exitDialog != null) {
            exitDialog.dismiss();
            exitDialog = null;
        }


    }
}
